/*
** Filesystem interface which goes to stdio by default. Eventually this will cover other things,
** such as zip files.
*/

#include "smse2kincludes.h"
#include "Debug.h"
#include "FileSystem.h"

void CBaseFileSystem::CloseFile(FILE_HANDLE file) {
	fclose((FILE*)file);
}

void CBaseFileSystem::Seek(FILE_HANDLE file,UINT32 offset) {
	fseek((FILE*)file, offset, SEEK_SET);
}

int CBaseFileSystem::Mount(const char *path) {
	Msg("ERROR: CFileSystem::Mount cannot be called directly\n");
	return 1;
}

UINT64 CBaseFileSystem::Read(FILE_HANDLE file, UINT8* buf, UINT32 readsize) {
	return fread(buf,readsize,1,(FILE*)file);
}

UINT64 CBaseFileSystem::Write(FILE_HANDLE file, UINT8* buf, UINT32 writesize) {
	return fwrite(buf,writesize,1,(FILE*)file);
}

UINT64 CBaseFileSystem::GetFileSize(FILE_HANDLE fHandle) {
	// Store current position in file
	UINT64 curpos = ftell((FILE*)fHandle);
	UINT64 fSize;

	// Now calculate the thing
	fseek((FILE*)fHandle,0,SEEK_END);
	fSize = ftell((FILE*)fHandle);

	// Seek back to where we were and return
	fseek((FILE*)fHandle,curpos,SEEK_SET);
	return fSize;
}

FILE_HANDLE CBaseFileSystem::OpenFile(const char *fn, UINT32 permission) {
			FILE* f; 	
			if (FSYS_PERMISSION_WRITE && FSYS_PERMISSION_READ) f = fopen(fn,"r+b");
			else if (FSYS_PERMISSION_WRITE) f = fopen(fn,"wb");
			else if (FSYS_PERMISSION_READ) f = fopen(fn,"rb");
			

			if (!f) Msg("error opening %s\n",fn);
			
			return f;
}

CBaseFileSystem filesystem;